package com.gree.framework.config;


import com.gree.framework.annotation.User;
import com.gree.framework.utils.SecurityUtils;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

/**
 * @ClassName UserArgumentResolver
 * @Description TODO
 * @Author ThreadNew
 * @Date 2020/11/20 15:23
 * Version 1.0
 **/
@Service
public class UserArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(User.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        Method method = methodParameter.getMethod();
        Parameter[] parameters = method.getParameters();
        for (Parameter parameter : parameters) {
            User annotation = parameter.getAnnotation(User.class);
            if (annotation != null) {
                Class clazz = annotation.value();//自定义注解
                Class<?> type = parameter.getType();
                if (type == clazz) {
                    return SecurityUtils.getUser().getUser();
                }
            }
        }


        return null;
    }
}
